/*******************************************************************************
 * Package: com.hngtrust.iir.homepage.controller
 * Type:    HomePageController
 * Date:    2021/3/29 9:58
 *
 * Copyright (c) 2021 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.hngtrust.iir.homepage.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hngtrust.aqc.business.service.AqcCompanyService;
import com.hngtrust.aqc.business.service.AqcRegService;
import com.hngtrust.clickhouse.news.dto.QuerySentimentByNewsIdDTO;
import com.hngtrust.clickhouse.news.entity.AppNews;
import com.hngtrust.clickhouse.news.entity.AppNewsSentiment;
import com.hngtrust.clickhouse.news.service.AppNewsSentimentService;
import com.hngtrust.clickhouse.news.service.AppNewsService;
import com.hngtrust.clickhouse.notice.service.AppNoticeService;
import com.hngtrust.clickhouse.report.dto.CollectionDTO;
import com.hngtrust.clickhouse.report.entity.AppReport;
import com.hngtrust.clickhouse.report.entity.AppReportSentiment;
import com.hngtrust.clickhouse.report.service.AppReportSentimentService;
import com.hngtrust.clickhouse.report.service.AppReportService;
import com.hngtrust.clickhouse.report.service.CrawlerReportService;
import com.hngtrust.dzh.business.service.TqExptAnntfileService;
import com.hngtrust.framework.bind.ResponseInfo;
import com.hngtrust.framework.page.PageResult;
import com.hngtrust.framework.page.service.PageService;
import com.hngtrust.framework.security.util.SecurityUtils;
import com.hngtrust.iir.base.dto.SystemModuleDTO;
import com.hngtrust.iir.base.dto.SystemTrendDTO;
import com.hngtrust.iir.base.entity.Dict;
import com.hngtrust.iir.base.service.DictService;
import com.hngtrust.iir.base.service.OptLogService;
import com.hngtrust.iir.company.dto.CompCountDTO;
import com.hngtrust.iir.company.dto.CompProvinceDTO;
import com.hngtrust.iir.company.dto.CustomerIndustryDTO;
import com.hngtrust.iir.company.dto.HomePageDynamicRespVO;
import com.hngtrust.iir.company.entity.CompDept;
import com.hngtrust.iir.company.entity.CompRisk;
import com.hngtrust.iir.company.entity.Company;
import com.hngtrust.iir.company.service.CompDeptService;
import com.hngtrust.iir.company.service.CompPortraitService;
import com.hngtrust.iir.company.service.CompRiskService;
import com.hngtrust.iir.company.service.CompanyService;
import com.hngtrust.iir.constant.Constant;
import com.hngtrust.iir.dto.ReqDTO;
import com.hngtrust.iir.homepage.controller.dto.CollectionReqVO;
import com.hngtrust.iir.homepage.controller.dto.CompCountReqVO;
import com.hngtrust.iir.homepage.controller.dto.CompCountResVO;
import com.hngtrust.iir.homepage.controller.dto.CompDataRespVO;
import com.hngtrust.iir.homepage.controller.dto.CustomerListReqVO;
import com.hngtrust.iir.homepage.controller.dto.CustomerListRespVO;
import com.hngtrust.iir.homepage.controller.dto.CustomerMessageRespVO;
import com.hngtrust.iir.homepage.controller.dto.DataDetailReqVO;
import com.hngtrust.iir.homepage.controller.dto.InterfaceMonitorRespVO;
import com.hngtrust.iir.homepage.controller.dto.NewsDataRespVO;
import com.hngtrust.iir.homepage.controller.dto.NoticeDataRespVO;
import com.hngtrust.iir.homepage.controller.dto.ReportDataRespVO;
import com.hngtrust.iir.homepage.controller.dto.SystemModuleReqVO;
import com.hngtrust.iir.homepage.controller.dto.SystemTrendReqVO;
import com.hngtrust.iir.news.controller.dto.ListNewsRespVO;
import com.hngtrust.iir.report.controller.dto.ListReportRespVO;
import com.hngtrust.iir.risk.entity.RiskMonitor;
import com.hngtrust.iir.risk.entity.RiskType;
import com.hngtrust.iir.risk.service.RiskMonitorService;
import com.hngtrust.iir.risk.service.RiskTypeService;
import com.hngtrust.iir.user.entity.TagRel;
import com.hngtrust.iir.user.entity.User;
import com.hngtrust.iir.user.service.TagRelService;
import com.hngtrust.iir.util.DateUtils;
import com.hngtrust.iir.util.ElkUtils;
import com.hngtrust.iir.util.HtmlUtils;
import com.hngtrust.wind.business.service.AshareanninfService;
import com.tiger.util.MyHttpClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 首页信息
 *
 * @author Keqiwei
 * @date 2021/3/29 9:58
 */
@Slf4j
@Api(tags = "首页信息")
@RestController
@RequestMapping("/home-page")
public class HomePageController {
    
    
    private static final MyHttpClient MY_HTTP_CLIENT = new MyHttpClient();
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    
    @Value("${elk.search.url:}")
    private String elkUrl;
    
    //研报索引名称
    @Value("${elk.search.indexname.report:}")
    private String indexReportName;
    
    //公告索引名称
    @Value("${elk.search.indexname.notice:}")
    private String indexNoticeName;
    
    //新闻资讯索引名称
    @Value("${elk.search.indexname.news:}")
    private String indexNewsName;
    
    @Value("${elk.search.indexname.comp}")
    private String indexCompName;
    
    @Autowired
    private AppNoticeService noticeService;
    
    @Autowired
    private CompPortraitService compPortraitService;
    
    @Autowired
    private CompanyService companyService;

    @Autowired
    private AqcRegService aqcRegService;

    @Autowired
    private AqcCompanyService aqcCompanyService;
    
    @Autowired
    private CompDeptService deptService;
    
    @Autowired
    private AppNewsService appNewsService;
    
    @Autowired
    private OptLogService optLogService;
    
    @Autowired
    private AppNoticeService appNoticeService;
    
    @Autowired
    private AppReportService appReportService;
    @Autowired
    private CrawlerReportService crawlerReportService;
    
    @Value("${ai.researchReportProcessing.url}")
    private String url;
    
    @Autowired
    private PageService pageService;
    
    @Autowired
    private AppNewsSentimentService appNewsSentimentService;
    
    @Autowired
    private AppReportSentimentService appReportSentimentService;
    
    @Value("${tiger.minio.out.address}")
    private String minioAddress;
    
    @Autowired
    private RiskTypeService typeService;
    
    @Autowired
    private TagRelService tagRelService;
    
    
    
    @Autowired
    private CompRiskService riskService;
    
    @Autowired
    private RiskMonitorService monitorService;
    
    @Autowired
    private DictService dictService;
    
   
    
    @ApiOperation(value = "机构客户信息")
    @PostMapping("/customer-message")
    public ResponseInfo<CustomerMessageRespVO> customerMessage(){
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        CustomerMessageRespVO respVO = new CustomerMessageRespVO();
        CompDept dept = new CompDept();
        dept.setDeptId(loginUser.getDeptId());
        List<Long> creditCodes = deptService.queryList(dept).stream().map(c -> c.getCompId()).collect(Collectors.toList());
        if (creditCodes.isEmpty()){
            respVO.setCustomerNum(0);
            respVO.setActiveCustomerNum(0L);//活跃客户数量
            respVO.setPrecipitateCustomerNum(0L);//沉淀客户数量
    
            respVO.setFiftyMillion(0L);//资本大于五千万客户数量
    
            respVO.setThirtyMillion(0L);//资本三千万到五千万客户数量
    
            respVO.setTenMillion(0L);//资本一千万到三千万客户数量
    
            respVO.setFiveMillion(0L);//资本五百万到一千万客户数量
    
            respVO.setZero(0L);//资本0到五百万客户数量
           return new ResponseInfo<>(respVO);
        }
        
        
        respVO.setCustomerNum(creditCodes.size());
        log.info("当前用户"+loginUser.getName()+"该部门下的机构客户数量"+creditCodes.size());
        respVO.setActiveCustomerNum(compPortraitService.activeCustomerNum(creditCodes));//活跃客户数量
        respVO.setPrecipitateCustomerNum(compPortraitService.precipitateCustomerNum(creditCodes));//沉淀客户数量
    
        respVO.setFiftyMillion(companyService.fiftyMillion(creditCodes));//资本大于五千万客户数量
    
        respVO.setThirtyMillion(companyService.thirtyMillion(creditCodes));//资本三千万到五千万客户数量
    
        respVO.setTenMillion(companyService.tenMillion(creditCodes));//资本一千万到三千万客户数量
    
        respVO.setFiveMillion(companyService.fiveMillion(creditCodes));//资本五百万到一千万客户数量
    
        respVO.setZero(companyService.zero(creditCodes));//资本0到五百万客户数量
    
        List<CustomerIndustryDTO> companies = companyService.customerIndustry(creditCodes);
        
        respVO.setCustomerIndustries(companies);
        return new ResponseInfo<CustomerMessageRespVO>(respVO);
    }
    
    @ApiOperation("机构相关新闻")
    @PostMapping("/customer-news")
    public ResponseInfo<PageResult<ListNewsRespVO>> customerNews(@ApiParam("分页参数") @RequestBody ReqDTO<Object> reqDTO){
        PageResult<ListNewsRespVO> pageResult = new PageResult();
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        CompDept dept = new CompDept();
        dept.setDeptId(loginUser.getDeptId());
        List<String> compId = deptService.queryList(dept).stream().map(d -> d.getCompId().toString()).collect(Collectors.toList());
        if (compId.isEmpty()){
            return new ResponseInfo<>(pageResult);
        }
        
        
        
        PageResult<AppNews> page = pageService.page(reqDTO.getPageParam(), () -> appNewsService.queryByCompIds(compId));
        List<ListNewsRespVO> news = new ArrayList<>();
        for (AppNews appNews :page.getRows()){
            ListNewsRespVO respDTO = new ListNewsRespVO();
            BeanUtils.copyProperties(appNews,respDTO);
            
            respDTO.setHtml(HtmlUtils.replaceHtmlTag(appNews.getHtml(),minioAddress));
        
            TagRel tagRel = new TagRel();
            tagRel.setDataType(Constant.TAG_DATATYPE_NEWS);
            tagRel.setDataId(appNews.getId());
            List<TagRel> tagRels = tagRelService.queryList(tagRel);
        
            AppNewsSentiment sentiment = new AppNewsSentiment();
            sentiment.setNewsId(appNews.getId());
            
           
            if(null != appNews.getSentiment()){
                if (Constant.SENTIMENT_POSITIVE.equals(appNews.getSentiment())) {
                    respDTO.setSentiment("积极");
                }
                if (Constant.SENTIMENT_NEUTRAL.equals(appNews.getSentiment())) {
                    respDTO.setSentiment("中立");
                }
                if (Constant.SENTIMENT_NEGATIVE.equals(appNews.getSentiment())) {
                    respDTO.setSentiment("消极");
                }
            }
            respDTO.setLabels(tagRels);
            List<QuerySentimentByNewsIdDTO> dtos = appNewsSentimentService
                    .querySentimentByNewsId(appNews.getId());
            if (dtos.size() >10 ){
                dtos = dtos.subList(0,10);
            }
            respDTO.setCompNames(dtos);
            news.add(respDTO);
        }
        List<ListNewsRespVO> collect = news.stream().distinct().collect(Collectors.toList());
        pageResult.setRows(collect);
        pageResult.setPage(page.getPage());
        return new ResponseInfo<>(pageResult);
   }
   
   
    @ApiOperation("机构相关研报")
    @PostMapping("/customer-report")
    public ResponseInfo<PageResult<ListReportRespVO>> customerReport(@ApiParam("分页参数") @RequestBody ReqDTO req){
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        CompDept dept = new CompDept();
        dept.setDeptId(loginUser.getDeptId());
        List<String> compId = deptService.queryList(dept).stream().map(d -> d.getCompId().toString()).collect(Collectors.toList());
        
        PageResult<ListReportRespVO> pageResult = new PageResult<>();
        if (compId.isEmpty()){
            return new ResponseInfo<>(pageResult);
        }
        
        List<ListReportRespVO> list = new ArrayList<>();
        PageResult<AppReport> page = pageService.page(req.getPageParam(), ()-> appReportService.queryByIds(compId));
        for (AppReport report : page.getRows()) {
            ListReportRespVO respVO= new ListReportRespVO();
            BeanUtils.copyProperties(report,respVO);
            TagRel tagRel = new TagRel();
            tagRel.setDataType(Constant.TAG_DATATYPE_REPORT);
            tagRel.setDataId(report.getId());
            if (report.getFilePath() != null && !report.getFilePath().isEmpty()){
                respVO.setFilePath(HtmlUtils.filePathAppend(report.getFilePath(),url));
            }
            respVO.setLabels(tagRelService.queryList(tagRel));
            AppReportSentiment appReportSentiment = new AppReportSentiment();
            appReportSentiment.setReportId(report.getId());
            List<String> compIds = appReportSentimentService.queryList(appReportSentiment).stream()
                    .map(a -> a.getCompId()).collect(Collectors.toList());
            List<String> compNames = appReportSentimentService.queryList(appReportSentiment).stream()
                    .map(a -> a.getEntity()).collect(Collectors.toList());
            if (respVO.getHtml() != null && respVO.getHtml() != ""){
                respVO.setHtml(HtmlUtils.replaceHtmlTag(respVO.getHtml(),minioAddress));
            }
            respVO.setCompIds(compIds);
            respVO.setCompNames(compNames);
            list.add(respVO);
        }
        
        pageResult.setRows(list);
        pageResult.setPage(page.getPage());
        return new ResponseInfo(pageResult);
    }
   
    
    
    @ApiOperation("首页最新动态")
    @PostMapping("/new-dynamic")
    public ResponseInfo<List<HomePageDynamicRespVO>> newsDynamic(){
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        
        List<Long> deptComp = deptService.queryByDept(loginUser.getDeptId());
        RiskMonitor monitor = new RiskMonitor();
        monitor.setStatus(Constant.DEFAULT_STATUS_NORMAL);
        monitor.setCreateUserId(loginUser.getId());
        List<Long> compId = monitorService.queryList(monitor).stream().map(c -> c.getCompId())
                .collect(Collectors.toList());
        deptComp.addAll(compId);
        if (deptComp.isEmpty()){
            return new ResponseInfo();
        }
        String date = DateUtils.format(new Date(), DateUtils.DATE);
        List<CompRisk> compRisks = riskService.queryNewDynamic(deptComp,date);
        log.info(loginUser.getUserCode()+"最新动态数"+compRisks.size());
        List<HomePageDynamicRespVO> list = new ArrayList<>();
        for (CompRisk compRisk : compRisks) {
            RiskType type = typeService.queryById(compRisk.getRiskTypeId());
            HomePageDynamicRespVO respVO = new HomePageDynamicRespVO();
            if(null != compRisk.getCompId()){
                respVO.setCompId(compRisk.getCompId());
            }
            if(null != compRisk.getCompName()){
                respVO.setCompName(compRisk.getCompName());
            }
            if(null != compRisk.getAnnDate()){
                respVO.setBuildTime(compRisk.getAnnDate());
            }
            if(null != compRisk.getRiskTypeId()){
                respVO.setRiskClass(type.getRiskClass());
            }
            
            list.add(respVO);
            
        }
        list = list.stream().sorted((a,b)-> -a.getBuildTime().compareTo(b.getBuildTime())).collect(Collectors.toList());
        return new ResponseInfo(list);
    }
    
    
    
    @ApiOperation("机构客户列表")
    @PostMapping("/list-customer")
    public ResponseInfo<PageResult<CustomerListRespVO>> listCustomer(@ApiParam("请求参数") @RequestBody ReqDTO<CustomerListReqVO> reqDTO){
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        log.error("查询公司类型"+reqDTO.getContent().getStatus());
        PageResult<CustomerListRespVO> pageResult = new PageResult<>();
        CompDept dept = new CompDept();
        dept.setDeptId(loginUser.getDeptId());
        List<Long> compIds = deptService.queryList(dept).stream().map(d -> d.getCompId()).collect(Collectors.toList());
        
        if (compIds.isEmpty()) {
            return new ResponseInfo<>(pageResult);
        }
        if (Constant.DEFAULT_STATUS_NORMAL.equals(reqDTO.getContent().getStatus())){
            compIds = compPortraitService.queryActiveCustomer(compIds).stream().map(c->c.getCompId()).collect(Collectors.toList());
            log.info(loginUser.getUserCode()+"活跃公司数量" + compIds.size());
        }
        if (Constant.DEFAULT_STATUS_DELETE.equals(reqDTO.getContent().getStatus())){
            compIds = compPortraitService.queryPrecipitateCustomer(compIds).stream().map(c->c.getCompId()).collect(Collectors.toList());
            log.info(loginUser.getUserCode()+"沉淀客户数量"+compIds.size());
        }
        
        if (compIds.isEmpty()){
            return new ResponseInfo(pageResult);
        }
        
        List<Long> finalCompIds = compIds;
        
        log.info(loginUser.getUserCode()+"机构总数"+finalCompIds.size());
        PageResult<Company> page = pageService.page(reqDTO.getPageParam(),
                () -> companyService.queryCustomer(finalCompIds, reqDTO.getContent().getCompName()));
        List<CustomerListRespVO> list = new ArrayList<>();
        Map<String, Dict> dictMap = dictService.queryDict("MANAGE_STATE");
        
        page.getRows().forEach(p->{
            CustomerListRespVO vo = new CustomerListRespVO();
            BeanUtils.copyProperties(p,vo);
            if (null != p.getLogo() && p.getLogo() != ""){
                vo.setLogo(minioAddress+p.getLogo());
            }
            if(null != p.getManageState() && null != dictMap && null != dictMap.get(p.getManageState().toString())){
                vo.setManageStateName(dictMap.get(p.getManageState().toString()).getBusiName());
            }
            list.add(vo);
        });
        pageResult.setPage(page.getPage());
        pageResult.setRows(list);
        return new ResponseInfo(pageResult);
    }
    
    @ApiOperation("公司统计")
    @PostMapping("/comp-count")
    public ResponseInfo<CompCountResVO> compCount(@ApiParam("请求参数") @Valid @RequestBody CompCountReqVO vo){
        CompCountResVO resVO = new CompCountResVO();
        resVO.setComp(companyService.count());
        resVO.setHnComp(companyService.countClient());
        if (vo.getCompType() == 1){
            List<CompProvinceDTO> compProvinceDTOS = companyService.countCompBYProvince(null);
            resVO.setProvince(compProvinceDTOS);
            if (vo.getQueryType() ==1){
                
                List<CompCountDTO> ranking = new ArrayList<>();
                long count = 0;
                for (int i = 0; i < compProvinceDTOS.size(); i++) {
                    compProvinceDTOS.get(i).setRank(i+1);
                    CompCountDTO compCountDTO = new CompCountDTO();
                    BeanUtils.copyProperties(compProvinceDTOS.get(i),compCountDTO);
                    count= count+compCountDTO.getCount();
                    compCountDTO.setScale(new BigDecimal(0));
                    ranking.add(compCountDTO);
                }
                if (count != 0){
                    BigDecimal bigDecimal = new BigDecimal(count);
                    ranking.forEach(r->{
                        BigDecimal divide = new BigDecimal(r.getCount())
                                .divide(bigDecimal, 4, BigDecimal.ROUND_CEILING).multiply(new BigDecimal(100));
        
                        
                        r.setScale(divide);
                    });
                }
                resVO.setRanking(ranking);
            }else {
               
                for (int i = 0; i < compProvinceDTOS.size(); i++) {
                    compProvinceDTOS.get(i).setRank(i+1);
                }
                resVO.setProvince(compProvinceDTOS);
                List<CompCountDTO> pms = companyService.countCompByIndustry(null);
                Long count = 0L;
                for (CompCountDTO pm : pms) {
                    count=count+pm.getCount();
                    pm.setScale(new BigDecimal(0));
                }
                if (count!=0){
                    BigDecimal b = new BigDecimal(count);
                    pms.forEach(p->{
                        BigDecimal multiply = new BigDecimal(p.getCount()).divide(b, 4, BigDecimal.ROUND_CEILING)
                                .multiply(new BigDecimal(100));
                        p.setScale(multiply);
                    });
                }
                resVO.setRanking(pms);
            }
            
        }
        
        
        if (vo.getCompType() == 2){
    
            if (vo.getQueryType() ==1){
                List<CompProvinceDTO> compProvinceDTOS = companyService.countCompBYProvince("pms");
                resVO.setProvince(compProvinceDTOS);
                List<CompCountDTO> ranking = new ArrayList<>();
                long count = 0;
                for (int i = 0; i < compProvinceDTOS.size(); i++) {
                    if (compProvinceDTOS.get(i).getCount()==null){
                        compProvinceDTOS.get(i).setCount(0L);
                    }
                    compProvinceDTOS.get(i).setRank(i+1);
                    CompCountDTO compCountDTO = new CompCountDTO();
                    BeanUtils.copyProperties(compProvinceDTOS.get(i),compCountDTO);
                    count=count+compCountDTO.getCount();
                    compCountDTO.setScale(new BigDecimal(0));
                    ranking.add(compCountDTO);
                }
                if (count != 0){
                    BigDecimal bigDecimal = new BigDecimal(count);
                    ranking.forEach(r->{
                        BigDecimal divide = new BigDecimal(r.getCount())
                                .divide(bigDecimal, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
                        
    
                        r.setScale(divide);
                    });
                }
                resVO.setRanking(ranking);
            }else {
                List<CompProvinceDTO> compProvinceDTOS = companyService.countCompBYProvince("pms");
                for (int i = 0; i < compProvinceDTOS.size(); i++) {
                    if (compProvinceDTOS.get(i).getCount()==null){
                        compProvinceDTOS.get(i).setCount(0L);
                    }
                    compProvinceDTOS.get(i).setRank(i+1);
                }
                resVO.setProvince(compProvinceDTOS);
                List<CompCountDTO> pms = companyService.countCompByIndustry("pms");
                long count = 0L;
                for (CompCountDTO pm : pms) {
                    count=count+pm.getCount();
                    pm.setScale(new BigDecimal(0));
                }
                if (count!=0){
                    BigDecimal b = new BigDecimal(count);
                    pms.forEach(p->{
                        BigDecimal multiply = new BigDecimal(p.getCount()).divide(b, 4, BigDecimal.ROUND_CEILING)
                                .multiply(new BigDecimal(100));
                        p.setScale(multiply);
                    });
                }
                resVO.setRanking(pms);
            }
        }
        return new ResponseInfo(resVO);
    }
 
    @ApiOperation("采集趋势")
    @PostMapping("/collection")
    public ResponseInfo<List<CollectionDTO>> collection(@ApiParam("请求参数") @Valid @RequestBody CollectionReqVO vo) {
        String beginTime = null ;
        String endTime = null ;
    
        if (Constant.COMP_RISK_TIME_DAY.equals(vo.getType())) {
            beginTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -6), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 0), DatePattern.NORM_DATE_PATTERN);
        } else if (Constant.COMP_RISK_TIME_WEEK.equals(vo.getType())) {
            beginTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -14), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 0), DatePattern.NORM_DATE_PATTERN);
        } else if (Constant.COMP_RISK_TIME_MONTH.equals(vo.getType())) {
            beginTime = DateUtil.format(DateUtil.offsetMonth(DateUtil.date(), -1), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 0), DatePattern.NORM_DATE_PATTERN);
        }else if(vo.getType() == 4){
            beginTime = DateUtil.format(DateUtil.offsetMonth(DateUtil.date(), -6), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 0), DatePattern.NORM_DATE_PATTERN);
        }else if (vo.getType() ==5){
            beginTime = DateUtil.format(DateUtil.offsetMonth(DateUtil.date(), -12), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 0), DatePattern.NORM_DATE_PATTERN);
        }
        List<CollectionDTO> count = crawlerReportService.count(beginTime, endTime);
        if (Constant.COMP_RISK_TIME_DAY.equals(vo.getType())) {
            String time = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -6), DatePattern.NORM_DATE_PATTERN);
            for (int i = 0; i < 7; i++) {
                String add = DateUtils.add(time, i);
                List<CollectionDTO> collect = count.stream().filter(c -> {
                    if (c.getTime().equals(add)) {
                        return true;
                    } else {
                        return false;
                    }
                }).collect(Collectors.toList());
                if (collect.isEmpty() || count.isEmpty()){
                    CollectionDTO dto = new CollectionDTO();
                    dto.setRatio(new BigDecimal(0));
                    dto.setNews(0L);
                    dto.setNotice(0L);
                    dto.setReport(0L);
                    dto.setTime(add);
                    count.add(dto);
                }
            }
            
        } else if (Constant.COMP_RISK_TIME_WEEK.equals(vo.getType())) {
            String time = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -14), DatePattern.NORM_DATE_PATTERN);
            for (int i = 0; i < 15; i++) {
                String add = DateUtils.add(time, i);
                List<CollectionDTO> collect = count.stream().filter(c -> {
                    if (c.getTime().equals(add)) {
                        return true;
                    } else {
                        return false;
                    }
                }).collect(Collectors.toList());
                if (collect.isEmpty()|| count.isEmpty()){
                    CollectionDTO dto = new CollectionDTO();
                    dto.setRatio(new BigDecimal(0));
                    dto.setNews(0L);
                    dto.setNotice(0L);
                    dto.setReport(0L);
                    dto.setTime(add);
                    count.add(dto);
                }
            }
        } else if (Constant.COMP_RISK_TIME_MONTH.equals(vo.getType())) {
            String time = DateUtil.format(DateUtil.offsetMonth(DateUtil.date(), -1), DatePattern.NORM_DATE_PATTERN);
            for (int i = 0; i < 30; i++) {
                String add = DateUtils.add(time, i);
                List<CollectionDTO> collect = count.stream().filter(c -> {
                    if (c.getTime().equals(add)) {
                        return true;
                    } else {
                        return false;
                    }
                }).collect(Collectors.toList());
                if (collect.isEmpty() || count.isEmpty()){
                    CollectionDTO dto = new CollectionDTO();
                    dto.setRatio(new BigDecimal(0));
                    dto.setNews(0L);
                    dto.setNotice(0L);
                    dto.setReport(0L);
                    dto.setTime(add);
                    count.add(dto);
                }
            }
        }else if(vo.getType() == 4){
    
            String time = DateUtil.format(DateUtil.offsetMonth(DateUtil.date(), -6), DatePattern.NORM_DATE_PATTERN);
            for (int i = 0; i < 183; i++) {
                String add = DateUtils.add(time, i);
                List<CollectionDTO> collect = count.stream().filter(c -> {
                    if (c.getTime().equals(add)) {
                        return true;
                    } else {
                        return false;
                    }
                }).collect(Collectors.toList() );
                if (collect.isEmpty() || count.isEmpty()){
                    CollectionDTO dto = new CollectionDTO();
                    dto.setRatio(new BigDecimal(0));
                    dto.setNews(0L);
                    dto.setNotice(0L);
                    dto.setReport(0L);
                    dto.setTime(add);
                    count.add(dto);
                }
            }
            
            
        }else if (vo.getType() ==5){
            String time = DateUtil.format(DateUtil.offsetMonth(DateUtil.date(), -12), DatePattern.NORM_DATE_PATTERN);
            for (int i = 0; i < 365; i++) {
                String add = DateUtils.add(time, i);
                List<CollectionDTO> collect = count.stream().filter(c -> {
                    if (c.getTime().equals(add)) {
                        return true;
                    } else {
                        return false;
                    }
                }).collect(Collectors.toList());
                if (collect.isEmpty() || count.isEmpty()){
                    CollectionDTO dto = new CollectionDTO();
                    dto.setRatio(new BigDecimal(0));
                    dto.setNews(0L);
                    dto.setNotice(0L);
                    dto.setReport(0L);
                    dto.setTime(add);
                    count.add(dto);
                }
            }
        }
        
        for (int i = 0; i < count.size(); i++) {
            if (i==0){
                count.get(i).setRatio(new BigDecimal(0));
            }else {
                Long l = count.get(i).getNews()+count.get(i).getNotice()+ count.get(i).getReport();
                Long l1 = count.get(i-1).getNews()+count.get(i-1).getNotice()+ count.get(i-1).getReport();
                if (l1==0){
                    count.get(i).setRatio(new BigDecimal(l));
                }else {
                    BigDecimal divide = new BigDecimal(l - l1).divide(new BigDecimal(l1), 4, BigDecimal.ROUND_CEILING).multiply(new BigDecimal(100));
                    count.get(i).setRatio(divide);
                }
                
                
            }
            
        }
        count = count.stream().sorted((a,b)->a.getTime().compareTo(b.getTime())).collect(Collectors.toList());
        return new ResponseInfo(count);
    }
    
    
    @ApiOperation("系统使用频率")
    @PostMapping("/system-module")
    public ResponseInfo<List<SystemModuleDTO>> systemModule(@ApiParam("请求参数") @Valid @RequestBody SystemModuleReqVO vo){
        String beginTime = null ;
        String endTime = null;
        if (vo.getType().equals(Constant.COMP_RISK_TIME_DAY)){
            beginTime  = DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 1), DatePattern.NORM_DATE_PATTERN);
        }
        List<SystemModuleDTO> systemModuleDTOS = optLogService.countSystemModule(beginTime, endTime);
        Map<String, Dict> sysModule = dictService.queryDict("SYS_MODULE");
        if (!systemModuleDTOS.isEmpty()){
            Long count = 0L;
            for (SystemModuleDTO s : systemModuleDTOS) {
                count = count+s.getCount();
                Dict dict = sysModule.get(s.getModule().toString());
                s.setModuleName(dict.getBusiName());
            }
            BigDecimal b = new BigDecimal(count);
            systemModuleDTOS.forEach(s->{
                BigDecimal divide = new BigDecimal(s.getCount()).divide(b, 4, BigDecimal.ROUND_CEILING).multiply(new BigDecimal(100));
                s.setRatio(divide);
            });
        }else {
            for (Map.Entry<String, Dict> e : sysModule.entrySet()) {
                SystemModuleDTO dto = new SystemModuleDTO();
                dto.setRatio(new BigDecimal(0));
                dto.setCount(0L);
                dto.setModuleName(e.getValue().getBusiName());
                systemModuleDTOS.add(dto);
            }
        }
        return new ResponseInfo(systemModuleDTOS);
    }
    
    @ApiOperation("系统使用趋势")
    @PostMapping("/system-trend")
    public ResponseInfo<List<SystemTrendDTO>> systemTrend(@ApiParam("请求参数") @Valid @RequestBody SystemTrendReqVO vo){
        String beginTime = null;
        String endTime = null;
        if (Constant.COMP_RISK_TIME_DAY.equals(vo.getType())) {
            beginTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -6), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 0), DatePattern.NORM_DATE_PATTERN)+" 23:59:59";
        } else if (Constant.COMP_RISK_TIME_WEEK.equals(vo.getType())) {
            beginTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -14), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 0), DatePattern.NORM_DATE_PATTERN)+" 23:59:59";
        } else if (Constant.COMP_RISK_TIME_MONTH.equals(vo.getType())) {
            beginTime = DateUtil.format(DateUtil.offsetMonth(DateUtil.date(), -1), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 0), DatePattern.NORM_DATE_PATTERN)+" 23:59:59";
        }else if (vo.getType() == 4){
            beginTime = DateUtil.format(DateUtil.offsetMonth(DateUtil.date(), -6), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 0), DatePattern.NORM_DATE_PATTERN)+" 23:59:59";
        }else if (vo.getType() == 5){
            beginTime = DateUtil.format(DateUtil.offsetMonth(DateUtil.date(), -12), DatePattern.NORM_DATE_PATTERN);
            endTime = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), 0), DatePattern.NORM_DATE_PATTERN)+" 23:59:59";
        }
        
        List<SystemTrendDTO> systemTrendDTOS = optLogService.countSystemTrend(beginTime, endTime);
    
        if (Constant.COMP_RISK_TIME_DAY.equals(vo.getType())) {
            String time = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -6), DatePattern.NORM_DATE_PATTERN);
            for (int i = 0; i < 7; i++) {
                String add = DateUtils.add(time, i);
                List<SystemTrendDTO> collect = systemTrendDTOS.stream().filter(c -> {
                    if (c.getTime().equals(add)) {
                        return true;
                    } else {
                        return false;
                    }
                }).collect(Collectors.toList());
                if (collect.isEmpty() || systemTrendDTOS.isEmpty()){
                    SystemTrendDTO dto = new SystemTrendDTO();
                    dto.setRatio(new BigDecimal(0));
                    dto.setCount(0L);
                    dto.setTime(add);
                    systemTrendDTOS.add(dto);
                }
            }
        
        } else if (Constant.COMP_RISK_TIME_WEEK.equals(vo.getType())) {
            String time = DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -14), DatePattern.NORM_DATE_PATTERN);
            for (int i = 0; i < 15; i++) {
                String add = DateUtils.add(time, i);
                List<SystemTrendDTO> collect = systemTrendDTOS.stream().filter(c -> {
                    if (c.getTime().equals(add)) {
                        return true;
                    } else {
                        return false;
                    }
                }).collect(Collectors.toList());
                if (collect.isEmpty() || systemTrendDTOS.isEmpty()){
                    SystemTrendDTO dto = new SystemTrendDTO();
                    dto.setRatio(new BigDecimal(0));
                    dto.setCount(0L);
                    dto.setTime(add);
                    systemTrendDTOS.add(dto);
                }
            }
        } else if (Constant.COMP_RISK_TIME_MONTH.equals(vo.getType())) {
            String time = DateUtil.format(DateUtil.offsetMonth(DateUtil.date(), -1), DatePattern.NORM_DATE_PATTERN);
            for (int i = 0; i < 30; i++) {
                String add = DateUtils.add(time, i);
                List<SystemTrendDTO> collect = systemTrendDTOS.stream().filter(c -> {
                    if (c.getTime().equals(add)) {
                        return true;
                    } else {
                        return false;
                    }
                }).collect(Collectors.toList());
                if (collect.isEmpty() || systemTrendDTOS.isEmpty()){
                    SystemTrendDTO dto = new SystemTrendDTO();
                    dto.setRatio(new BigDecimal(0));
                    dto.setCount(0L);
                    dto.setTime(add);
                    systemTrendDTOS.add(dto);
                }
            }
        }else if(vo.getType() == 4){
        
            String time = DateUtil.format(DateUtil.offsetMonth(DateUtil.date(), -6), DatePattern.NORM_DATE_PATTERN);
            for (int i = 0; i < 183; i++) {
                String add = DateUtils.add(time, i);
                List<SystemTrendDTO> collect = systemTrendDTOS.stream().filter(c -> {
                    if (c.getTime().equals(add)) {
                        return true;
                    } else {
                        return false;
                    }
                }).collect(Collectors.toList());
                if (collect.isEmpty()  || systemTrendDTOS.isEmpty()){
                    SystemTrendDTO dto = new SystemTrendDTO();
                    dto.setRatio(new BigDecimal(0));
                    dto.setCount(0L);
                    dto.setTime(add);
                    systemTrendDTOS.add(dto);
                }
            }
        
        
        }else if (vo.getType() ==5){
            String time = DateUtil.format(DateUtil.offsetMonth(DateUtil.date(), -12), DatePattern.NORM_DATE_PATTERN);
            for (int i = 0; i < 365; i++) {
                String add = DateUtils.add(time, i);
                List<SystemTrendDTO> collect = systemTrendDTOS.stream().filter(c -> {
                    if (c.getTime().equals(add)) {
                        return true;
                    } else {
                        return false;
                    }
                }).collect(Collectors.toList());
                if (collect.isEmpty() || systemTrendDTOS.isEmpty()){
                    SystemTrendDTO dto = new SystemTrendDTO();
                    dto.setRatio(new BigDecimal(0));
                    dto.setCount(0L);
                    dto.setTime(add);
                    systemTrendDTOS.add(dto);
                }
            }
        }
    
    
    
        for (int i = 0; i < systemTrendDTOS.size(); i++) {
            if(i==0){
                systemTrendDTOS.get(i).setRatio(new BigDecimal(0));
            }else {
                Long l = systemTrendDTOS.get(i).getCount()-systemTrendDTOS.get(i-1).getCount();
                BigDecimal b= new BigDecimal(l);
                if (systemTrendDTOS.get(i - 1).getCount() == 0){
                    systemTrendDTOS.get(i).setRatio(new BigDecimal(0));
                }else {
                    BigDecimal divide = b
                            .divide(new BigDecimal(systemTrendDTOS.get(i - 1).getCount()), 4, BigDecimal.ROUND_CEILING).multiply(new BigDecimal(100));
                    systemTrendDTOS.get(i).setRatio(divide);
                }
                
            }
        }
    
        List<SystemTrendDTO> collect = systemTrendDTOS.stream().sorted(Comparator.comparing(SystemTrendDTO::getTime))
                .collect(Collectors.toList());
        return new ResponseInfo(collect);
    }
    
    
    @ApiOperation("接口监控")
    @PostMapping("/interface-monitor")
    public ResponseInfo<InterfaceMonitorRespVO> interfaceMonitor(){
        
        String beginTime  = DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN);
        String endTime = DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN);
        InterfaceMonitorRespVO wind = new InterfaceMonitorRespVO();
        wind.setSource("wind");
//        Long aLong = appNoticeService.countEtlSource(beginTime, endTime+" 23:59:59","wind");
        Long aLong = appNoticeService.countEtlSource(beginTime, endTime+" 23:59:59");
        if (aLong == 0){
            Long l = appNoticeService.countEtlSource(beginTime+" 09:00:00", endTime + " 23:59:59");
            wind.setCollection(Collections.singletonList("暂无数据"));
            wind.setSource("wind");
            if (l == 0){
                wind.setStatus("异常");
            }else {
                wind.setStatus("监控中");
            }
        }else {
            wind.setCollection(Collections.singletonList("公告"+aLong));
            wind.setSource("wind");
            wind.setStatus("正常");
        }
        
        InterfaceMonitorRespVO report = new InterfaceMonitorRespVO();
        Long r = appReportService.countSource(beginTime, endTime + " 23:59:59","大智慧");
        if (r==0){
            Long l = appReportService.countSource(beginTime + " 09:00:00", endTime + " 23:59:59","大智慧");
        
                report.setSource("大智慧");
                report.setCollection(Collections.singletonList("暂无数据"));
                if (l==0){
                    report.setStatus("--");
                }else {
                    report.setStatus("监控中");
                }
            
        }else {
            report.setSource("大智慧");
            report.setCollection(Collections.singletonList("大智慧"+r));
            report.setStatus("正常");
        }
        
        Long comCount = aqcCompanyService.countComSource(beginTime, endTime + " 23:59:59");
        Long regCount = aqcRegService.countRegSource(beginTime, endTime + " 23:59:59");
        Long c = comCount+regCount;
        InterfaceMonitorRespVO company = new InterfaceMonitorRespVO();
        if (c==0){
            Long comCount1 = aqcCompanyService.countComSource(beginTime, endTime + " 23:59:59");
            Long regCount1 = aqcRegService.countRegSource(beginTime, endTime + " 23:59:59");
            company.setSource("爱企查");
            company.setCollection(Collections.singletonList("暂无数据"));
            if (comCount1==0 && regCount1 ==0){
                company.setStatus("异常");
            }else {
                company.setStatus("监控中");
            }
        }else {
            company.setSource("爱企查");
            company.setCollection(Collections.singletonList("公司"+c));
            company.setStatus("正常");
        }
        
    
        InterfaceMonitorRespVO internet = new InterfaceMonitorRespVO();
        Long ri = appReportService.countNetCrawlerApp(beginTime, endTime + " 23:59:59");
        Long ni = appNoticeService.countCrawlerSource(beginTime, endTime + " 23:59:59");
        Long news = appNewsService.countCrawlerNet(beginTime,endTime+" 23:59:59");
        if (ri != 0 && ni != 0 && news != 0){
            internet.setCollection(Arrays.asList("公告"+ni,"研报"+ri,"新闻"+news));
            internet.setStatus("正常");
            internet.setSource("爬虫");
        }else {
//            Long ri1 = appReportService.countInternet(beginTime+" 09:00:00", endTime + " 23:59:59");
//            Long ni1 = appNoticeService.countSource(beginTime+" 09:00:00", endTime + " 23:59:59", "爬虫");
//            Long news1 = appNewsService.count(beginTime+" 09:00:00",endTime+" 23:59:59");
            if (ri == 0 && ni == 0 && news == 0){
                internet.setCollection(Arrays.asList("公告"+ni,"研报"+ri,"新闻"+news));
                internet.setStatus("异常");
                internet.setSource("爬虫");
            }else {
                internet.setCollection(Arrays.asList("公告"+ni,"研报"+ri,"新闻"+news));
                internet.setStatus("监控中");
                internet.setSource("爬虫");
            }
        }
        List<InterfaceMonitorRespVO> list = new ArrayList<>();
        list.add(wind);
        list.add(report);
        list.add(company);
        list.add(internet);
        return new ResponseInfo(list);
    }
   
    @Autowired
    //wind
    private AshareanninfService ashareanninfService;
    
    @Autowired
    //dazhihui
    private TqExptAnntfileService tqExptAnntfileService;
    
    @ApiOperation("研报数据详情")
    @PostMapping("/report-detail")
    public ResponseInfo<ReportDataRespVO> reportDetail(@ApiParam("请求参数") @Valid @RequestBody DataDetailReqVO vo)
            throws JsonProcessingException {
        Long start = DateUtil.parse(vo.getTime()).getTime();
        Long end = DateUtil.parse(vo.getTime() + " 23:59:59").getTime();
        JSONObject params = new JSONObject();
        JSONObject time = new JSONObject();
        time.put(ElkUtils.ELK_GRAMMAR_GTE, start);
        time.put(ElkUtils.ELK_GRAMMAR_LTE, end);
        JSONObject range = new JSONObject();
        JSONObject jj = new JSONObject();
        jj.put("iir.iir_publishtime",time);
        range.put(ElkUtils.ELK_GRAMMAR_RANGE,jj);
        JSONObject email = new JSONObject();
        JSONObject j = new JSONObject();
        j.put("iir.iir_data_source","研报邮箱");
        email.put(ElkUtils.ELK_GRAMMAR_MATCH_PHRASE,j);
        JSONObject collect = new JSONObject();
        JSONObject ff =  new JSONObject();
        ff.put("iir.iir_data_source","互联网采集");
        collect.put(ElkUtils.ELK_GRAMMAR_MATCH_PHRASE,ff);
        List<JSONObject> should = new ArrayList<>();
        should.add(email);
        should.add(collect);
        JSONObject boolS = new JSONObject();
        boolS.put(ElkUtils.ELK_GRAMMAR_SHOULD,should);
        JSONObject bool = new JSONObject();
        bool.put(ElkUtils.ELK_GRAMMAR_BOOL,boolS);
        List<JSONObject> mustl = new ArrayList<>();
        mustl.add(range);
        mustl.add(bool);
        JSONObject must = new JSONObject();
        must.put(ElkUtils.ELK_GRAMMAR_MUST,mustl);
        JSONObject booll = new JSONObject();
        booll.put("bool",must);
        params.put(ElkUtils.ELK_GRAMMAR_QUERY,booll);
        log.info("查询参数:{}",params.toString());
        String httpUrl = null;
        if (elkUrl.endsWith("/") || elkUrl.endsWith("\\")) {
            httpUrl = elkUrl + indexReportName + "/" + ElkUtils.ELK_GRAMMAR_SEARCH;
        } else {
            httpUrl = elkUrl + "/" + indexReportName + "/" + ElkUtils.ELK_GRAMMAR_SEARCH;
        }
        log.info("研报查询参数{0}"+params.toString());
        String content = MY_HTTP_CLIENT.postJson(httpUrl, params);
        JsonNode jsonNode = OBJECT_MAPPER.readTree(content);
        JsonNode hits = jsonNode.get("hits");
        JsonNode total = hits.get("total");
        Long netValue = total.get("value").asLong();
    
        JSONObject dazhihui = new JSONObject();
        JSONObject f = new JSONObject();
        f.put("iir.iir_data_source","大智慧");
        dazhihui.put(ElkUtils.ELK_GRAMMAR_MATCH_PHRASE,f);
        JSONObject params1 = new JSONObject();
        List<JSONObject> should1 = new ArrayList<>();
        should1.add(dazhihui);
        JSONObject boolS1 = new JSONObject();
        boolS1.put(ElkUtils.ELK_GRAMMAR_SHOULD,should1);
        JSONObject bool1 = new JSONObject();
        bool1.put(ElkUtils.ELK_GRAMMAR_BOOL,boolS1);
        List<JSONObject> mustl1 = new ArrayList<>();
        mustl1.add(range);
        mustl1.add(bool1);
        JSONObject must1 = new JSONObject();
        must1.put(ElkUtils.ELK_GRAMMAR_MUST,mustl1);
        JSONObject booll1 = new JSONObject();
        booll1.put("bool",must1);
        params1.put(ElkUtils.ELK_GRAMMAR_QUERY,booll1);
        log.info("研报查询参数1{0}"+params1.toString());
        String content1 = MY_HTTP_CLIENT.postJson(httpUrl, params1);
        JsonNode jsonNode1 = OBJECT_MAPPER.readTree(content1);
        JsonNode hits1 = jsonNode1.get("hits");
        JsonNode total1 = hits1.get("total");
        Long dValue = total1.get("value").asLong();
    
        ReportDataRespVO vo1 = new ReportDataRespVO();
        vo1.setDElk(dValue);
        vo1.setNetElk(netValue);
        vo1.setDazhihui(tqExptAnntfileService.countDzh(vo.getTime(),vo.getTime()+ " 23:59:59"));
        vo1.setAAiBefore(appReportService.countDAiAfter(vo.getTime(),vo.getTime()+ " 23:59:59"));
        vo1.setDAiAfter(appReportService.countDAiBefore(vo.getTime(),vo.getTime()+ " 23:59:59"));
        vo1.setNet(appReportService.countNet(vo.getTime(),vo.getTime()+ " 23:59:59"));
        vo1.setNetAiAfter(appReportService.countNetAi(vo.getTime(),vo.getTime()+ " 23:59:59"));
        vo1.setAppReport(appReportService.countDzh(vo.getTime(),vo.getTime()+" 23:59:59"));
        vo1.setNetAppReport(appReportService.countNetApp(vo.getTime(),vo.getTime()+" 23:59:59"));
        return new ResponseInfo(vo1);
    }
    
   
    @ApiOperation("公告数据详情")
    @PostMapping("/notice-detail")
    public ResponseInfo<NoticeDataRespVO> noticeDetail(@ApiParam("请求参数") @Valid @RequestBody DataDetailReqVO vo)
            throws JsonProcessingException {
        Long start = DateUtil.parse(vo.getTime()).getTime();
        Long end = DateUtil.parse(vo.getTime() + " 23:59:59").getTime();
        JSONObject params = new JSONObject();
        JSONObject time = new JSONObject();
        time.put(ElkUtils.ELK_GRAMMAR_GTE, start);
        time.put(ElkUtils.ELK_GRAMMAR_LTE, end);
        JSONObject range = new JSONObject();
        JSONObject filed = new JSONObject();
        filed.put("iir.iir_publishtime",time);
        range.put(ElkUtils.ELK_GRAMMAR_RANGE,filed);
        JSONObject email = new JSONObject();
        JSONObject f = new JSONObject();
        f.put("iir.iir_data_source","爬虫");
        email.put(ElkUtils.ELK_GRAMMAR_MATCH_PHRASE,f);
        List<JSONObject> should = new ArrayList<>();
        should.add(email);
        JSONObject boolS = new JSONObject();
        boolS.put(ElkUtils.ELK_GRAMMAR_SHOULD,should);
        JSONObject bool = new JSONObject();
        bool.put(ElkUtils.ELK_GRAMMAR_BOOL,boolS);
        List<JSONObject> mustl = new ArrayList<>();
        mustl.add(range);
        mustl.add(bool);
        JSONObject must = new JSONObject();
        must.put(ElkUtils.ELK_GRAMMAR_MUST,mustl);
        JSONObject booll = new JSONObject();
        booll.put("bool",must);
        params.put(ElkUtils.ELK_GRAMMAR_QUERY,booll);
        log.info("查询参数:{}",params.toString());
        String httpUrl = null;
        if (elkUrl.endsWith("/") || elkUrl.endsWith("\\")) {
            httpUrl = elkUrl + indexNoticeName + "/" + ElkUtils.ELK_GRAMMAR_SEARCH;
        } else {
            httpUrl = elkUrl + "/" + indexNoticeName + "/" + ElkUtils.ELK_GRAMMAR_SEARCH;
        }
        log.info("公告查询参数{0}"+params.toString());
        String content = MY_HTTP_CLIENT.postJson(httpUrl, params);
        JsonNode jsonNode = OBJECT_MAPPER.readTree(content);
        JsonNode hits = jsonNode.get("hits");
        JsonNode total = hits.get("total");
        Long netValue = total.get("value").asLong();
        
        
        JSONObject params1 = new JSONObject();
        JSONObject wind = new JSONObject();
        JSONObject f1 = new JSONObject();
        f1.put("iir.iir_data_source","wind");
        wind.put(ElkUtils.ELK_GRAMMAR_MATCH_PHRASE,f1);
        List<JSONObject> should1 = new ArrayList<>();
        should1.add(wind);
        JSONObject boolS1 = new JSONObject();
        boolS1.put(ElkUtils.ELK_GRAMMAR_SHOULD,should1);
        JSONObject bool1 = new JSONObject();
        bool1.put(ElkUtils.ELK_GRAMMAR_BOOL,boolS1);
        List<JSONObject> mustl1 = new ArrayList<>();
        mustl1.add(range);
        mustl1.add(bool1);
        JSONObject must1 = new JSONObject();
        must1.put(ElkUtils.ELK_GRAMMAR_MUST,mustl1);
        JSONObject booll1 = new JSONObject();
        booll1.put("bool",must1);
        params1.put(ElkUtils.ELK_GRAMMAR_QUERY,booll1);
        log.info("公告查询参数1{0}"+params1.toString());
        String content1 = MY_HTTP_CLIENT.postJson(httpUrl, params1);
        JsonNode jsonNode1 = OBJECT_MAPPER.readTree(content1);
        JsonNode hits1 = jsonNode1.get("hits");
        JsonNode total1 = hits1.get("total");
        Long windValue = total1.get("value").asLong();
    
        NoticeDataRespVO vo1 = new NoticeDataRespVO();
        //wind elk
        vo1.setElk(windValue);
        // 采集elk
        vo1.setNetElk(netValue);
        // wind
        vo1.setWind(ashareanninfService.countWind(vo.getTime(),vo.getTime()+ " 23:59:59"));
        // wind ai处理后
        vo1.setAiAfter((appNoticeService.countWindAi1(vo.getTime(),vo.getTime()+ " 23:59:59"))+
                (appNoticeService.countWindAi1Not(vo.getTime(),vo.getTime()+ " 23:59:59")));
        // wind ai处理前
        vo1.setAiBefore(appNoticeService.countWindAi(vo.getTime(),vo.getTime()+ " 23:59:59"));

        // 采集数
        vo1.setNet(appNoticeService.countNet(vo.getTime(),vo.getTime()+ " 23:59:59"));
        // 采集ai处理后
        vo1.setNetAiAfter((appNoticeService.countNetAi(vo.getTime(),vo.getTime()+ " 23:59:59"))+
                (appNoticeService.countNetAiNot(vo.getTime(),vo.getTime()+ " 23:59:59"))
        );
        // 投研库
        vo1.setAppNotice(appNoticeService.countWind(vo.getTime(),vo.getTime()+ " 23:59:59","wind"));
        // 采集投研库
        vo1.setNetAppNotice(appNoticeService.countWind(vo.getTime(),vo.getTime()+ " 23:59:59","爬虫"));
        return new ResponseInfo(vo1);
    }
    
    @ApiOperation("新闻数据详情")
    @PostMapping("/news-detail")
    public ResponseInfo<NewsDataRespVO> newsDetail(@ApiParam("请求参数") @Valid @RequestBody DataDetailReqVO vo)
            throws JsonProcessingException {
    
        Long start = DateUtil.parse(vo.getTime()).getTime();
        Long end = DateUtil.parse(vo.getTime() + " 23:59:59").getTime();
        JSONObject params = new JSONObject();
        JSONObject time = new JSONObject();
        time.put(ElkUtils.ELK_GRAMMAR_GTE, start);
        time.put(ElkUtils.ELK_GRAMMAR_LTE, end);
        JSONObject range = new JSONObject();
        JSONObject jj  = new JSONObject();
        jj.put("iir.iir_publishtime",time);
        range.put(ElkUtils.ELK_GRAMMAR_RANGE,jj);
        params.put(ElkUtils.ELK_GRAMMAR_QUERY,range);
        log.info("新闻查询参数:{}",params.toString());
        String httpUrl = null;
        if (elkUrl.endsWith("/") || elkUrl.endsWith("\\")) {
            httpUrl = elkUrl + indexNewsName + "/" + ElkUtils.ELK_GRAMMAR_SEARCH;
        } else {
            httpUrl = elkUrl + "/" + indexNewsName + "/" + ElkUtils.ELK_GRAMMAR_SEARCH;
        }
        String content = MY_HTTP_CLIENT.postJson(httpUrl, params);
        JsonNode jsonNode = OBJECT_MAPPER.readTree(content);
        JsonNode hits = jsonNode.get("hits");
        JsonNode total = hits.get("total");
        Long netValue = total.get("value").asLong();
        NewsDataRespVO vo1 = new NewsDataRespVO();
        vo1.setElk(netValue);
        vo1.setNet(appNewsService.countAll(vo.getTime(),vo.getTime()+" 23:59:59"));
        vo1.setAi(appNewsService.countAI(vo.getTime(),vo.getTime()+" 23:59:59"));
        vo1.setAppNews(appNewsService.countNet(vo.getTime(),vo.getTime()+" 23:59:59"));
        return new ResponseInfo(vo1);
    }
    
    @ApiOperation("公司数据详情")
    @PostMapping("/comp-detail")
    public ResponseInfo<CompDataRespVO> compDetail(@ApiParam("请求参数") @Valid @RequestBody DataDetailReqVO vo)
            throws JsonProcessingException {
        Long start = DateUtil.parse(vo.getTime()).getTime();
        Long end = DateUtil.parse(vo.getTime() + " 23:59:59").getTime();
        JSONObject params = new JSONObject();
        JSONObject time = new JSONObject();
        time.put(ElkUtils.ELK_GRAMMAR_GTE, start);
        time.put(ElkUtils.ELK_GRAMMAR_LTE, end);
        JSONObject range = new JSONObject();
        
        JSONObject filed = new JSONObject();
        filed.put("iir.iir_publishtime",time);
        range.put(ElkUtils.ELK_GRAMMAR_RANGE,filed);
        params.put(ElkUtils.ELK_GRAMMAR_QUERY,range);
        String httpUrl = null;
        if (elkUrl.endsWith("/") || elkUrl.endsWith("\\")) {
            httpUrl = elkUrl + indexCompName + "/_count";
        } else {
            httpUrl = elkUrl + "/" + indexCompName + "/_count";
        }
        log.info("公司查询参数{0}"+params.toString());
        String content = MY_HTTP_CLIENT.postJson(httpUrl, params);
        JsonNode jsonNode = OBJECT_MAPPER.readTree(content);
        CompDataRespVO vo1 = new CompDataRespVO();
        Long elkComp = jsonNode.get("count").asLong();
        Long windComp = ashareanninfService.countAdd(vo.getTime(), vo.getTime() + " 23:59:59");
        Long windCount = ashareanninfService.countAll();
        Long windUpdate = ashareanninfService.countUpdate(vo.getTime(), vo.getTime() + " 23:59:59");
        vo1.setWindAdd(windComp);
        vo1.setWindCount(windCount);
        vo1.setWindUpdate(windUpdate);
        vo1.setElkCount(elkComp);
        Long aqcAdd = appReportService.countAdd(vo.getTime(), vo.getTime() + " 23:59:59");
        Long aqcUpdate = appReportService.countUpdate(vo.getTime(), vo.getTime() + " 23:59:59");
        Long aqcAll = appReportService.countAll();
        vo1.setAqcAdd(aqcAdd);
        vo1.setAqcCount(aqcAll);
        vo1.setAqcUpdate(aqcUpdate);
        vo1.setTyUpdate(companyService.countUpdate(vo.getTime(), vo.getTime() + " 23:59:59"));
        vo1.setTyCount(companyService.countAll());
    
        return new ResponseInfo(vo1);
    }
}
